package org.ghub.pdf;

import java.io.IOException;

import com.itextpdf.text.pdf.PdfArray;
import com.itextpdf.text.pdf.PdfDictionary;
import com.itextpdf.text.pdf.PdfIndirectReference;
import com.itextpdf.text.pdf.PdfName;
import com.itextpdf.text.pdf.PdfReader;

public class pdfExtractTree {
	
	private int page = 1;

	public pdfExtractTree() {
	}

	public static void main(String[] args) throws IOException {
		PdfReader reader = new PdfReader("src/main/resources/Condicionado Salud de Oro Marzo 2010 (AM SO 02-10).pdf");
		PdfDictionary dict = reader.getCatalog();
		PdfDictionary pageroot = dict.getAsDict(PdfName.PAGES);
		new pdfExtractTree().expand(pageroot);
		}		
		
		 public void expand(PdfDictionary dict) {
		 if (dict == null)
		 return;
		 PdfIndirectReference ref = dict.getAsIndirectObject(PdfName.PARENT);
		 if (dict.isPage()) {
		 System.out.println("Child of " + ref + ": PAGE " + (page++));
		 }
		 else if (dict.isPages()) {
		 if (ref == null)
		 System.out.println("PAGES ROOT");
		 else
		 System.out.println("Child of " + ref + ": PAGES");
		 PdfArray kids = dict.getAsArray(PdfName.KIDS);
		 System.out.println(kids);
		 if (kids != null) {
		 for (int i = 0; i < kids.size(); i++) {
		 expand(kids.getAsDict(i));
		 }
		 }
		 }
		 }

		public int getPage() {
			return page;
		}

		public void setPage(int page) {
			this.page = page;
		} 		 			

}
